#include "iic_driver.h"

void iic_driver_init(void)
{
  I2C_DeInit();
  I2C_Init(100000, 0x00, I2C_DUTYCYCLE_2, I2C_ACK_CURR, I2C_ADDMODE_7BIT, 16);
  I2C_Cmd(ENABLE);
}

uint8_t iic_driver_wait_even(I2C_Event_TypeDef even)
{
  uint8_t t=0;
  for(t=0;t<CLOCK_TIMEOUT&&!I2C_CheckEvent(even);t++);
  return t==CLOCK_TIMEOUT ? 1 : 0;
}

uint8_t iic_driver_wait_flag(I2C_Flag_TypeDef flag)
{
  uint8_t t=0;
  for(t=0;t<CLOCK_TIMEOUT&&I2C_GetFlagStatus(flag);t++);
  return t==CLOCK_TIMEOUT ? 1 : 0;
}

uint8_t iic_driver_write(uint8_t addr, uint8_t* data, uint8_t len)
{
  if(clock_wait_flag(I2C_FLAG_BUSBUSY)) return 1;
  I2C_GenerateSTART(ENABLE);
  if(clock_wait_even(I2C_EVENT_MASTER_MODE_SELECT)) return 2;
  I2C_Send7bitAddress(CLOCK_ADDR, I2C_DIRECTION_TX);
  if(clock_wait_even(I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) return 3;
  I2C_SendData(addr);
  while(len--)
  {
    if(clock_wait_even(I2C_EVENT_MASTER_BYTE_TRANSMITTED)) return 4;
    I2C_SendData(*data++);
  }
  if(clock_wait_even(I2C_EVENT_MASTER_BYTE_TRANSMITTED)) return 5;
  I2C_GenerateSTOP(ENABLE);
  return 0;
}

uint8_t iic_driver_read(uint8_t addr, uint8_t *data, uint8_t len)
{
  if(clock_wait_flag(I2C_FLAG_BUSBUSY)) return 1;
  I2C_GenerateSTART(ENABLE);
  if(clock_wait_even(I2C_EVENT_MASTER_MODE_SELECT)) return 2;
  I2C_Send7bitAddress(CLOCK_ADDR, I2C_DIRECTION_TX);
  if(clock_wait_even(I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)) return 3;
  I2C_SendData(addr);
  if(clock_wait_even(I2C_EVENT_MASTER_BYTE_TRANSMITTED)) return 3;
  I2C_GenerateSTART(ENABLE);
  if(clock_wait_even(I2C_EVENT_MASTER_MODE_SELECT)) return 4;
  I2C_Send7bitAddress(CLOCK_ADDR, I2C_DIRECTION_RX);
  if(clock_wait_even(I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED)) return 4;
  while(len--)
  {
    if(clock_wait_even(I2C_EVENT_MASTER_BYTE_RECEIVED)) return 4;
    *data = I2C_ReceiveData();
    data++;
  } 
  I2C_GenerateSTOP( ENABLE);
  return 0;
}